<script setup>

import { ref,onMounted } from 'vue'
import axios from 'axios'
import AddressDialog from "@/views/AddressDialog.vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter()
/**
 *  vue2 和 vue3 的写法:
 *    1、vue2 data、methods、mounted  api组件函数
 *    2、vue3  中 统一使用了 setup 语法 省略了上面的多个属性操作
 *
 *  数据的初始化:
 *     vue2   data() 函数进行初始化
 *     vue3   ref() 函数进行初始化 使用的时候    变量.value
 *            没有this 函数和属性都是直接使用
 */
const addressId = ref(0);   //要提交的收货地址，也是默认选中的地址
const addresses = ref([]);   //显示地址列表
const cart = ref({});        //购物车

//修改收货地址
const changeAddress = (addressId)=>{
  addressId.value = addressId;
}

//查询当前用户的所有收货地址
const initAddress = ()=> {
  axios.get("/address/findAddress").then(resp => {
    addresses.value = resp.data;
    //获取默认选中的地址id
    addresses.value.forEach(item => {
      if (item.isDefault == 1) {
        addressId.value = item.id;
      }
    });
  })
}

//获取购物车数据
const initCart = ()=>{
  axios.get("/cart/myCartDetails").then(resp => {
    cart.value = resp.data;
  })
}

onMounted(()=>{
  initAddress()
  initCart();
})

const dialogVisible = ref(false)

const showAddressDialog = ()=>{
  dialogVisible.value = true
}
//关闭对话框
const handleClose = (val)=> {
  //修改外部的值
  dialogVisible.value = val;
}
const initAddressData = ()=> {
  //后端查询所有收货地址
  axios.get('/address/findAddress').then((response) => {
    addresses.value = response.data;
    addresses.value.forEach(e => {
      if (e.isDefault == 1) {
        addressId.value = e.id;
      }
    });
  });
}

//提交订单
const submitOrder = ()=>{
  axios.post(`/order/createOrder/${addressId.value}`).then(resp => {
    //可以设置提交按钮不可用，2秒后再还原
    ElMessage.success(resp.data);
    //过2秒后再跳转
    setTimeout(() => {
      //跳转到订单列表页面
      router.push('/order').catch(error => error);
    }, 2000);
  }).catch(error => {
    //输出错误信息
    ElMessage.error(error.response.data);
  });
}


</script>

<template>
  <div class="main">
    <h1> 订单提交结算页面 </h1>
    <el-tag>收货地址</el-tag>
    <el-select v-model="addressId" placeholder="请选择收货地址"
               style="width: 400px" size="small">
      <el-option v-for="item in addresses"
                 :key="item.id" :value="item.id"
                 :label="item.label"
                 @change="changeAddress">
      </el-option>
    </el-select>
    <el-button style="margin-left: 10px;"
               type="success" @click="showAddressDialog"
               size="small">
      新增收货地址
    </el-button>


    <el-card class="cart">
      <el-table :data="cart.itemList" style="width: 100%" stripe highlight-current-row
                class="cart-table">

        <el-table-column type="index" width="55" label="序号">
          <template #default="{$index}">
            {{ $index + 1 }}
          </template>
        </el-table-column>

        <el-table-column prop="name" label="书名">
          <template #default="{row}">
            《{{ row.name }}》
          </template>
        </el-table-column>

        <el-table-column prop="image" label="图片">
          <template #default="{row}">
            <el-image style="height: 120px;"
                      :src="$urlImage + row.image"
                      fit="fit">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价">
          <template #default="{row}">
            &yen; {{ row.price.toFixed(2) }}
          </template>
        </el-table-column>


        <el-table-column prop="quantity" label="数量">
          <template #default="{row}">
            <el-tag type="danger">{{ row.quantity }}本</el-tag>
          </template>
        </el-table-column>


        <el-table-column prop="sum" label="金额">
          <template #default="{row}">
            &yen; {{ row.sum.toFixed(2) }}
          </template>
        </el-table-column>


      </el-table>

      <div class="cart-footer">
        <span>共有<span class="cart-number">{{ cart.amount }}</span>本书</span>
        <span>合计：<span style="color: red; font-size: 25px;">
          &yen; {{cart.totalPrice ? cart.totalPrice.toFixed(2) : 0 }}
         </span></span>
        <el-button type="primary" icon="el-icon-s-shop" @click="submitOrder">提交订单</el-button>
      </div>
    </el-card>

    <!-- 新增收货地址 -->
    <address-dialog
        :dialogVisible="dialogVisible"
        @close="handleClose" @reload-address="initAddressData"
    />

  </div>
</template>

<style scoped>
.main {
  padding: 5px;
}
</style>
